<template>
  <div>
    <el-form @submit.native.prevent :inline="true">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="主本名称"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="联系人"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-farm-org
          v-model="params['org_class.eq']"
          placeholder="主体类型"
          clearable
          @change="getData()"
          class="form-control-ml"
        ></select-farm-org>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="startDate"
          placeholder="申请起始时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="endDate"
          placeholder="申请截止时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('新农直通车')"
        >
          导出
        </el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button
          type="primary"
          v-if="isArchiveManager"
          icon="el-icon-upload2"
          @click="showImport"
        >
          导入
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      ref="table"
      class="table-sm"
      :columns="tableColumns"
      :data="tableData"
    ></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData()"
      ></el-pagination>
    </div>

    <import-excel
      :excel-template="importFileUrl"
      title="导入项目信息"
      :tip="false"
      :post-api="postUrl"
      :visible.sync="importVisible"
      @success="getData()"
    ></import-excel>

    <edit-dialog :visible.sync="editVisible" @success="getData()" :query-id="editId"></edit-dialog>

    <view-dialog :visible.sync="viewVisible" :query-id="queryId"></view-dialog>
  </div>
</template>

<script>
import ImportExcel from '@/components/ImportExcel'
import { queryTrouble } from '@vimi/utils-api'
import EditDialog from '@/gov/views/bus/import/xinnong/components/EditDialog'
import ViewDialog from '@/gov/views/bus/import/xinnong/components/ViewDialog'
import { mapGetters } from 'vuex'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
import SelectAddress from '@/components/select/SelectAddress'
import SelectFarmOrg from '@/components/select/SelectFarmOrg'
export default {
  components: {
    ImportExcel,
    EditDialog,
    ViewDialog,
    SelectAddress,
    SelectFarmOrg,
  },
  props: {},
  data() {
    return {
      params: {
        index: 1,
        size: 15,
        customer_name: '',
      },
      order: {
        create_time: 'DESC',
      },
      loading: false,
      totalCount: 0,
      tableData: [],
      tableColumns: [
        { attrs: { label: '主体名称', prop: 'customer_name' } },
        { attrs: { label: '经营地址', prop: 'address' } },
        { attrs: { label: '主体类型', prop: 'org_class_name' } },
        { attrs: { label: '联系人', prop: 'corp_name' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        { attrs: { label: '统一社会信用代码', prop: 'register_no' } },
        { attrs: { label: '申请金额(万元)', prop: 'apply_funds' } },
        { attrs: { label: '资金用途', prop: 'funds_use_dir' } },
        { attrs: { label: '申请时间', prop: 'createTime', width: '100px' } },
        {
          attrs: { label: '操作', align: 'center', width: 100 },
          operations: [
            {
              content: '编辑',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row => row.submit_person === this.userId,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger' },
              event: this.handleDelete,
              ifRender: row => row.submit_person === this.userId,
            },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
          ],
        },
      ],
      importVisible: false,
      tableName: 'credit_direct',
      editVisible: false,
      editId: '',
      viewVisible: false,
      queryId: '',
      exportLoading: false,
      startDate: '',
      endDate: '',
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'job', 'clientId']),
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode
    },
    importFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/新农直报导入模板.xlsx`
    },
    postUrl() {
      return (
        '/api/credit/import/' +
        queryTrouble(this.tableName, {
          importKey: 'credit_direct_template',
        })
      )
    },
    isArchiveManager() {
      return this.user.scopeArr.includes('dirReport')
    },
    isCorp() {
      return this.job === 'org_corp'
    },
  },
  watch: {},
  created() {
    if (this.isArchiveManager) {
      this.params['orWhere.address_code.endlike'] = this.queryAddressCode.replace(/0+$/g, '')
      this.params['orWhere.submit_person.eq'] = this.userId
    } else {
      this.params['submit_person.eq'] = this.userId
    }
    // this.params['orWhere.address_code.endlike'] = this.queryAddressCode.replace(/0+$/g, '')
    this.getData()
  },
  mounted() {},
  methods: {
    dateChange() {
      this.params['create_time.gte'] = this.startDate || ''
      this.params['create_time.lte'] = this.endDate ? this.endDate + ' 23:59:59' : ''
      this.getData()
    },
    showImport() {
      this.importVisible = true
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = (data?.data ?? []).map(this.dataAdapter)
          this.totalCount = data?.totalCount ?? 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.createTime = this.$utils.dateFormat(item.create_time, 'yyyy-MM-dd')
      return item
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    handleEdit(row = {}) {
      this.editId = row.credit_direct_id
      this.editVisible = true
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除主体${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.credit_direct_id),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    handleView(row = {}) {
      this.viewVisible = true
      this.queryId = row.credit_direct_id
    },
    async exportExcel(filename) {
      const exportTable = [
        { label: '序号', prop: 'index' },
        { label: '业务编号', prop: 'project_no' },
        { label: '贷款申请金额（万元）', prop: 'apply_funds' },
        { label: '资金用途', prop: 'funds_use_dir' },
        { label: '已有贷款余额（万元）', prop: 'left_loan_funds' },
        { label: '主体类型', prop: 'org_class_name' },
        { label: '主体名称', prop: 'customer_name' },
        { label: '主体等级', prop: 'customer_lever' },
        { label: '统一社会信用代码证号', prop: 'register_no' },
        { label: '家庭农场主/ 合作社实际经营人', prop: 'corp_name' },
        { label: '身份证号', prop: 'lender_idcard' },
        { label: '联系方式', prop: 'mobile_no' },
        { label: '经营地址', prop: 'address' },
        { label: '详细经营地址', prop: 'address_detail' },
        { label: '流转来的面积（亩）', prop: 'converse_area' },
        { label: '自营土地面积（亩）', prop: 'self_bus_area' },
        { label: '土地总面积（亩）', prop: 'solid_area_total' },
        { label: '年经营收入（万元）', prop: 'annual_income' },
        { label: '实际经营年限', prop: 'business_years' },
        { label: '主营业务类型', prop: 'main_business' },
        { label: '经营品种', prop: 'parent_main_business' },
        { label: '经营规模', prop: 'business_scale' },
        { label: '单位', prop: 'scale_unit' },
        { label: '面积（平方米）', prop: 'commercial_residential_building' },
        { label: '购置价（万元）', prop: 'buy_value' },
        { label: '宅基地面积（平方）', prop: 'house_area' },
        { label: '房屋建造成本（万元）', prop: 'build_cost' },
        { label: '面积（平方米）', prop: 'workshop_area' },
        { label: '建造成本（万元）', prop: 'workshop_cost' },
        { label: '数量', prop: 'ghouse_area' },
        { label: '大棚规格', prop: 'ghouse_spec' },
        { label: '建造成本（万元）', prop: 'ghouse_cost' },
        { label: '农机设备名称', prop: 'amachine_name' },
        { label: '农机设备价格（万元）', prop: 'amachine_price' },
        { label: '农机购置时间', prop: 'amachine_time' },
        { label: '品牌型号', prop: 'brand_model' },
        { label: '购置时间', prop: 'brand_purchase_time' },
        { label: '购置价格', prop: 'accumulation_price' },
        { label: '借款金额', prop: 'borrowing_balance' },
        { label: '期限', prop: 'load_years' },
        { label: '贷款机构', prop: 'lending_institution' },
        { label: '尚未偿还金额（万元）', prop: 'no_repay_funds' },
        { label: '额度（万元）', prop: 'limit_funds' },
        { label: '发卡机构', prop: 'card_issuer' },
        { label: '已使用额度（万元）', prop: 'used_funds' },
        { label: '担保金额（万元）', prop: 'amount_guaranteed' },
        { label: '期限', prop: 'gua_deadline' },
        { label: '贷款机构（包括但不限于银行）', prop: 'gua_lending_institution' },
        { label: '险种', prop: 'types_of_insurance' },
        { label: '投保面积/数量', prop: 'ins_spec' },
        { label: '保额（万元）', prop: 'coverage' },
        { label: '补贴类型', prop: 'subsidies_type' },
        { label: '补贴金额（万元）', prop: 'subsidies_funds' },
      ]
      const header = {}
      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}1`] = { font: { bold: true } }
        headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })
      this.exportLoading = true
      const { index, size, ...params } = this.params
      const [res = {}] = await this.fetchData(params)
      const title = {
        index: '序号',
        project_no: '业务编号',
        apply_funds: '申请融资信息',
        org_class_name: '基本信息',
        converse_area: '土地信息',
        annual_income: '经营信息',
        commercial_residential_building: '商品房',
        house_area: '农村住房',
        workshop_area: '厂房',
        ghouse_area: '大棚信息',
        amachine_name: '农机设备',
        brand_model: '车辆信息',
        borrowing_balance: '已有借款信息',
        limit_funds: '信用卡信息',
        amount_guaranteed: '对外担保情况',
        types_of_insurance: '农业保险信息',
        subsidies_type: '享受的农业补贴信息',
      }
      const data = (res.data || []).map((item, index) => {
        item.index = index + 1
        return item
      })

      excelJsonExport({
        columns,
        data: [title, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: [
          'A1:A2',
          'B1:B2',
          'C1:E1',
          'F1:N1',
          'O1:Q1',
          'R1:W1',
          'X1:Y1',
          'Z1:AA1',
          'AB1:AC1',
          'AD1:AF1',
          'AG1:AI1',
          'AJ1:AL1',
          'AM1:AP1',
          'AQ1:AS1',
          'AT1:AV1',
          'AW1:AY1',
          'AZ1:BA1',
        ],
        cellStyles: {
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
